<template>
  <el-dialog
    v-model="visible"
    :title="$t('pages.profile.title')"
    width="700px"
    :close-on-click-modal="false"
    @closed="handleClosed"
  >
    <el-tabs v-model="activeTab" class="profile-tabs">
      <!-- 基本信息 Tab -->
      <el-tab-pane :label="$t('pages.profile.tabs.basic')" name="basic">
        <el-form
          ref="basicFormRef"
          :model="basicForm"
          :rules="basicRules"
          label-width="140px"
        >
          <el-form-item :label="$t('pages.profile.basicInfo.name')" prop="name">
            <el-input
              v-model="basicForm.name"
              :placeholder="$t('pages.profile.basicInfo.namePlaceholder')"
            />
          </el-form-item>

          <el-form-item :label="$t('pages.profile.basicInfo.birthDate')" prop="birthDateFirst6">
            <el-input
              v-model="basicForm.birthDateFirst6"
              :placeholder="$t('pages.profile.basicInfo.birthDatePlaceholder')"
              maxlength="6"
            />
            <div class="form-hint">{{ $t('pages.profile.basicInfo.birthDateHint') }}</div>
          </el-form-item>

          <el-form-item :label="$t('pages.profile.basicInfo.idNumber')">
            <el-input
              :model-value="userInfo?.idNumber"
              disabled
              :placeholder="$t('pages.profile.basicInfo.idNumberReadonly')"
            />
          </el-form-item>

          <el-form-item :label="$t('pages.profile.basicInfo.tier')">
            <el-input
              :model-value="userInfo?.tier"
              disabled
              :placeholder="$t('pages.profile.basicInfo.tierReadonly')"
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSaveBasic" :loading="saving">
              {{ saving ? $t('pages.profile.saving') : $t('pages.profile.save') }}
            </el-button>
            <el-button @click="visible = false">{{ $t('pages.profile.cancel') }}</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 密码修改 Tab -->
      <el-tab-pane :label="$t('pages.profile.tabs.password')" name="password">
        <el-form
          ref="passwordFormRef"
          :model="passwordForm"
          :rules="passwordRules"
          label-width="140px"
        >
          <el-form-item :label="$t('pages.profile.password.oldPassword')" prop="oldPassword">
            <el-input
              v-model="passwordForm.oldPassword"
              type="password"
              :placeholder="$t('pages.profile.password.oldPasswordPlaceholder')"
              show-password
            />
          </el-form-item>

          <el-form-item :label="$t('pages.profile.password.newPassword')" prop="newPassword">
            <el-input
              v-model="passwordForm.newPassword"
              type="password"
              :placeholder="$t('pages.profile.password.newPasswordPlaceholder')"
              show-password
            />
            <div class="form-hint">{{ $t('pages.profile.password.passwordHint') }}</div>
          </el-form-item>

          <el-form-item :label="$t('pages.profile.password.confirmPassword')" prop="confirmPassword">
            <el-input
              v-model="passwordForm.confirmPassword"
              type="password"
              :placeholder="$t('pages.profile.password.confirmPasswordPlaceholder')"
              show-password
            />
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSavePassword" :loading="saving">
              {{ saving ? $t('pages.profile.saving') : $t('pages.profile.save') }}
            </el-button>
            <el-button @click="resetPasswordForm">{{ $t('pages.profile.cancel') }}</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 银行账户 Tab -->
      <el-tab-pane :label="$t('pages.profile.tabs.bankAccount')" name="bank">
        <el-form
          ref="bankFormRef"
          :model="bankForm"
          :rules="bankRules"
          label-width="140px"
        >
          <el-form-item :label="$t('pages.profile.bankAccount.bank')" prop="withdrawalBank">
            <el-select
              v-model="bankForm.withdrawalBank"
              :placeholder="$t('pages.profile.bankAccount.bankPlaceholder')"
              style="width: 100%"
            >
              <el-option label="KB국민은행" value="kb_kookmin" />
              <el-option label="신한은행" value="shinhan" />
              <el-option label="우리은행" value="woori" />
              <el-option label="하나은행" value="hana" />
              <el-option label="NH농협은행" value="nh_nonghyup" />
              <el-option label="IBK기업은행" value="ibk" />
              <el-option label="SC제일은행" value="sc_first" />
              <el-option label="씨티은행" value="citi" />
              <el-option label="KDB산업은행" value="kdb" />
              <el-option label="수출입은행" value="exim" />
              <el-option label="BNK부산은행" value="bnk_busan" />
              <el-option label="BNK경남은행" value="bnk_gyeongnam" />
              <el-option label="DGB대구은행" value="dgb_daegu" />
              <el-option label="광주은행" value="gwangju" />
              <el-option label="전북은행" value="jeonbuk" />
              <el-option label="제주은행" value="jeju" />
              <el-option label="카카오뱅크" value="kakao" />
              <el-option label="케이뱅크" value="k_bank" />
              <el-option label="토스뱅크" value="toss" />
              <el-option label="새마을금고" value="mg_saemaul" />
              <el-option label="수협은행" value="suhyup" />
              <el-option label="신협은행" value="shinhyup" />
              <el-option label="우체국" value="korea_post" />
            </el-select>
          </el-form-item>

          <el-form-item :label="$t('pages.profile.bankAccount.accountNumber')" prop="withdrawalAccount">
            <el-input
              v-model="bankForm.withdrawalAccount"
              :placeholder="$t('pages.profile.bankAccount.accountPlaceholder')"
            />
          </el-form-item>

          <el-form-item :label="$t('pages.profile.bankAccount.accountHolder')" prop="accountHolder">
            <el-input
              v-model="bankForm.accountHolder"
              :placeholder="$t('pages.profile.bankAccount.holderPlaceholder')"
            />
            <div class="form-hint">{{ $t('pages.profile.bankAccount.bankHint') }}</div>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSaveBank" :loading="saving">
              {{ saving ? $t('pages.profile.saving') : $t('pages.profile.save') }}
            </el-button>
            <el-button @click="visible = false">{{ $t('pages.profile.cancel') }}</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>

      <!-- 手机号 Tab -->
      <el-tab-pane :label="$t('pages.profile.tabs.mobile')" name="mobile">
        <el-form
          ref="mobileFormRef"
          :model="mobileForm"
          :rules="mobileRules"
          label-width="140px"
        >
          <el-form-item :label="$t('pages.profile.mobile.carrier')" prop="mobileCarrier">
            <el-select
              v-model="mobileForm.mobileCarrier"
              :placeholder="$t('pages.profile.mobile.carrierPlaceholder')"
              style="width: 100%"
            >
              <el-option label="SKT" value="skt" />
              <el-option label="KT" value="kt" />
              <el-option label="LG U+" value="lguplus" />
              <el-option label="SKT알뜰폰" value="skt_mvno" />
              <el-option label="KT알뜰폰" value="kt_mvno" />
              <el-option label="LGU알뜰폰" value="lgu_mvno" />
              <el-option label="알뜰폰 (기타)" value="mvno_other" />
            </el-select>
          </el-form-item>

          <el-form-item :label="$t('pages.profile.mobile.number')" prop="mobileNumber">
            <el-input
              v-model="mobileForm.mobileNumber"
              :placeholder="$t('pages.profile.mobile.numberPlaceholder')"
            />
            <div class="form-hint">{{ $t('pages.profile.mobile.mobileHint') }}</div>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" @click="handleSaveMobile" :loading="saving">
              {{ saving ? $t('pages.profile.saving') : $t('pages.profile.save') }}
            </el-button>
            <el-button @click="visible = false">{{ $t('pages.profile.cancel') }}</el-button>
          </el-form-item>
        </el-form>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, watch, computed } from 'vue'
import { ElMessage, type FormInstance, type FormRules } from 'element-plus'
import { useI18n } from 'vue-i18n'
import { userApiService, type UserInfo } from '@/services/userApi'

const { t } = useI18n()

// Props
interface Props {
  modelValue: boolean
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  (e: 'update:modelValue', value: boolean): void
  (e: 'updated'): void
}>()

// Computed
const visible = computed({
  get: () => props.modelValue,
  set: (value) => emit('update:modelValue', value)
})

// State
const activeTab = ref('basic')
const saving = ref(false)
const userInfo = ref<UserInfo | null>(null)

// Form Refs
const basicFormRef = ref<FormInstance>()
const passwordFormRef = ref<FormInstance>()
const bankFormRef = ref<FormInstance>()
const mobileFormRef = ref<FormInstance>()

// Forms
const basicForm = reactive({
  name: '',
  birthDateFirst6: ''
})

const passwordForm = reactive({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const bankForm = reactive({
  withdrawalBank: '',
  withdrawalAccount: '',
  accountHolder: ''
})

const mobileForm = reactive({
  mobileCarrier: '',
  mobileNumber: ''
})

const createRuleMessage = (key: string) => (_?: string) => t(key)

// Validation Rules
const basicRules: FormRules = {
  name: [
    { required: true, message: createRuleMessage('pages.profile.validation.nameRequired'), trigger: 'blur' }
  ],
  birthDateFirst6: [
    { required: true, message: createRuleMessage('pages.profile.validation.birthDateRequired'), trigger: 'blur' },
    { pattern: /^\d{6}$/, message: createRuleMessage('pages.profile.validation.birthDateFormat'), trigger: 'blur' }
  ]
}

const passwordRules: FormRules = {
  oldPassword: [
    { required: true, message: createRuleMessage('pages.profile.validation.oldPasswordRequired'), trigger: 'blur' }
  ],
  newPassword: [
    { required: true, message: createRuleMessage('pages.profile.validation.newPasswordRequired'), trigger: 'blur' },
    { min: 6, message: createRuleMessage('pages.profile.validation.newPasswordLength'), trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: createRuleMessage('pages.profile.validation.confirmPasswordRequired'), trigger: 'blur' },
    {
      validator: (_rule, value, callback) => {
        if (value !== passwordForm.newPassword) {
          callback(new Error(t('pages.profile.validation.passwordMismatch')))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

const bankRules: FormRules = {
  withdrawalBank: [
    { required: true, message: createRuleMessage('pages.profile.validation.bankRequired'), trigger: 'change' }
  ],
  withdrawalAccount: [
    { required: true, message: createRuleMessage('pages.profile.validation.accountRequired'), trigger: 'blur' }
  ],
  accountHolder: [
    { required: true, message: createRuleMessage('pages.profile.validation.holderRequired'), trigger: 'blur' }
  ]
}

const mobileRules: FormRules = {
  mobileCarrier: [
    { required: true, message: createRuleMessage('pages.profile.validation.carrierRequired'), trigger: 'change' }
  ],
  mobileNumber: [
    { required: true, message: createRuleMessage('pages.profile.validation.mobileRequired'), trigger: 'blur' }
  ]
}

// Methods
const loadUserInfo = async () => {
  try {
    userInfo.value = await userApiService.getUserInfo()

    // Fill forms with user data
    basicForm.name = userInfo.value.name
    basicForm.birthDateFirst6 = userInfo.value.birthDateFirst6

    bankForm.withdrawalBank = userInfo.value.withdrawalBank
    bankForm.withdrawalAccount = userInfo.value.withdrawalAccount
    bankForm.accountHolder = userInfo.value.accountHolder

    mobileForm.mobileCarrier = userInfo.value.mobileCarrier
    mobileForm.mobileNumber = userInfo.value.mobileNumber
  } catch (error) {
    ElMessage.error(t('pages.profile.loadError'))
  }
}

const handleSaveBasic = async () => {
  if (!basicFormRef.value) return

  try {
    await basicFormRef.value.validate()
    saving.value = true

    await userApiService.updateBasicInfo({
      name: basicForm.name,
      birthDateFirst6: basicForm.birthDateFirst6
    })

    ElMessage.success(t('pages.profile.saveSuccess'))
    emit('updated')
    await loadUserInfo()
  } catch (error: any) {
    if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error(t('pages.profile.saveError'))
    }
  } finally {
    saving.value = false
  }
}

const handleSavePassword = async () => {
  if (!passwordFormRef.value) return

  try {
    await passwordFormRef.value.validate()
    saving.value = true

    await userApiService.updatePassword({
      oldPassword: passwordForm.oldPassword,
      newPassword: passwordForm.newPassword
    })

    ElMessage.success(t('pages.profile.saveSuccess'))
    resetPasswordForm()
  } catch (error: any) {
    if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error(t('pages.profile.saveError'))
    }
  } finally {
    saving.value = false
  }
}

const handleSaveBank = async () => {
  if (!bankFormRef.value) return

  try {
    await bankFormRef.value.validate()
    saving.value = true

    await userApiService.updateBankAccount({
      withdrawalBank: bankForm.withdrawalBank,
      withdrawalAccount: bankForm.withdrawalAccount,
      accountHolder: bankForm.accountHolder
    })

    ElMessage.success(t('pages.profile.saveSuccess'))
    emit('updated')
    await loadUserInfo()
  } catch (error: any) {
    if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error(t('pages.profile.saveError'))
    }
  } finally {
    saving.value = false
  }
}

const handleSaveMobile = async () => {
  if (!mobileFormRef.value) return

  try {
    await mobileFormRef.value.validate()
    saving.value = true

    await userApiService.updateMobileNumber({
      mobileCarrier: mobileForm.mobileCarrier,
      mobileNumber: mobileForm.mobileNumber
    })

    ElMessage.success(t('pages.profile.saveSuccess'))
    emit('updated')
    await loadUserInfo()
  } catch (error: any) {
    if (error.message) {
      ElMessage.error(error.message)
    } else {
      ElMessage.error(t('pages.profile.saveError'))
    }
  } finally {
    saving.value = false
  }
}

const resetPasswordForm = () => {
  passwordForm.oldPassword = ''
  passwordForm.newPassword = ''
  passwordForm.confirmPassword = ''
  passwordFormRef.value?.clearValidate()
}

const handleClosed = () => {
  // Reset active tab
  activeTab.value = 'basic'
  resetPasswordForm()
}

// Watch for dialog open
watch(visible, (newValue) => {
  if (newValue) {
    loadUserInfo()
  }
})
</script>

<style scoped lang="scss">
.profile-tabs {
  :deep(.el-tabs__content) {
    padding: 20px 0;
  }
}

.form-hint {
  margin-top: 8px;
  font-size: 0.875rem;
  color: #64748b;
}

:deep(.el-form-item) {
  margin-bottom: 24px;
}

:deep(.el-input__inner) {
  border-radius: 8px;
}

:deep(.el-select) {
  width: 100%;
}
</style>
